<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/9/27
 * Time: 09:35
 */

namespace app\api\service;

use app\api\model\Product;
use app\lib\enum\OrderStatusEnum;
use think\Db;
use think\Exception;
use think\Loader;
use app\api\model\Order as OrderModel;
use think\Log;

//extend/WxPay/WxPay.Notify.php
Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class WxNotify extends \WxPayNotify
{
    /**
     * c重写支付处理函数
     * @param array $objData
     * @param string $msg
     * @return bool
     */
    public function NotifyProcess($data, $config ,&$msg)
    {
        $data = $data->GetValues();//获取对象中的数组
        if ($data['result_code'] == 'SUCCESS'){
            Db::startTrans();
            try{
                $orderInfo = OrderModel::getOrderInfoByOrderNo($data['out_trade_no']);
                if ($orderInfo->status == 1){
                    $service = new Order();
                    $stockStatus =  $service->checkOrderStack($orderInfo->id);//获取订单信息
                    if ($stockStatus['pass']){
                        $this->updateOrderStatus($orderInfo->id,true);//更新订单状态
                        $this->reduceStock($stockStatus);//减库存
                    }else{
                        $this->updateOrderStatus($orderInfo->id,false);
                    }
                }
                Db::commit();
                return true;
            }catch  (Exception $exception){
                Db::rollback();
                Log::error($exception);
                return false;
            }
        }else{
            return true;
        }
    }
    /**
     * 减库存
     * @param $status
     */
    private function reduceStock($status){
        foreach ($status['pStatusArray'] as $singleStatus){
            Product::reduceOrderNum($singleStatus['id'],$singleStatus['count']);
        }
    }
    /**
     * 跟新订单状态
     * @param $OrderID
     * @param $success
     */
    private function updateOrderStatus($OrderID,$success){
        $status =   $success?
            OrderStatusEnum::PAID:
            OrderStatusEnum::PAID_BUT_OUT_OF;
        $info=[
            'status'=>$status
        ];
        OrderModel::updateOrderByID($OrderID,$info);
    }
}